<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.min.css" rel="stylesheet" />
		<style type="text/css">
			html,
			body {
				height: 100%;
			}
			.mui-content {
				height: 100%;
				overflow: auto;
			}
			.red-point{
	          position: relative;
	        }
	
	        .red-point::before{
	          content: " ";
	          border: 5px solid red;/*设置红色*/
	          border-radius:5px;/*设置圆角*/
	          position: absolute;
	          z-index: 31000;
	          right: 0%;
	          margin-right: 3px;
	          margin-top:-3px;
	        }
		</style>
	</head>

	<body>
		<div class="mui-content">
			<ul id="ul_chatSnapshot" class="mui-table-view" style="margin-top: 0px;">
			</ul>
		</div>
		
		<script src="js/mui.min.js"></script>
		<script src="js/app.js"></script>
		<script src="js/aes_2.js"></script>
		<script type="text/javascript">
			mui.init();
			mui.plusReady(function() {
				// 监听当前webview的show事件
				CHAT.init()
				let myUserInfo = app.getUserInfo();
				mui("#ul_chatSnapshot").on("tap",".chat-with-friend",function(){
					// 打开聊天页面
					mui.openWindow({
						url: "chating/chatting.html",
						id: "chatting-" + this.getAttribute("friendUserId"),
						extras:{
							friendUserId : this.getAttribute("friendUserId"),
							friendNickName: this.getAttribute("friendNickName"),
							friendFaceImg: this.getAttribute("friendFaceImg")
						}
					})
					// 标记未读状态为已读
					app.readUserChatSnapshot(myUserInfo.userId,this.getAttribute("friendUserId"));
					// 渲染快照列表
					loadingChatSnapshot();
				});
				
				mui("#ul_chatSnapshot").on("tap","#link_delChatRecord",function(){
					let _this = this;
					// 删除本地聊天记录
					app.deleteUserChatHistory(myUserInfo.userId,_this.getAttribute("friendUserId"));
					// 删除本地快照
					app.deleteUserChatSnapshot(myUserInfo.userId,_this.getAttribute("friendUserId"))
					// 移除dom
					let li_dom = _this.parentNode.parentNode;
					let ul_dom = document.getElementById("ul_chatSnapshot");
					ul_dom.removeChild(li_dom);
				})
				window.addEventListener("refresh",function(){
					// 渲染快照列表
					loadingChatSnapshot();
				});
			});
			// 构建聊天记录
			window.CHAT={
				socket:null,
				init:function(){
					if(window.WebSocket){
						// 如果当前的状态已经连接，那就不需要重复初始化websocket
						if(CHAT.socket!=null && CHAT.socket!=undefined && CHAT.socket.readyState == WebSocket.OPEN){
							return false;
						}
						CHAT.socket = new WebSocket(app.msgServerUrl);
						CHAT.socket.onopen = CHAT.wsopen,
						CHAT.socket.onclose = CHAT.wsclose,
						CHAT.socket.onerror = CHAT.wserror,
						CHAT.socket.onmessage = CHAT.wsmessage;
					}
				},
				chat: function(msg){
					if(CHAT.socket!=null && CHAT.socket!=undefined && CHAT.socket.readyState == WebSocket.OPEN){
						CHAT.socket.send(msg);
					}else{
						CHAT.init()
						setTimeout(()=>{
							CHAT.socket.send(msg);
						},500)
					}
					// 渲染快照列表
					loadingChatSnapshot();
				},
				wsopen: function(){
					let myUserInfo = app.getUserInfo();
					// 构建 chatMsg dataContent
					let chatMsg = new app.chatMsg(myUserInfo.userId,null,null,null);
					let dataContent = new app.dataContent(app.CONNECT,chatMsg,null);
					// 发送websocket
					CHAT.chat(JSON.stringify(dataContent))
					// 拉取未读消息列表
					fetchUnReadMsg();
					setInterval("CHAT.keepAlive()",40000);
				},
				wsclose: function(){
					console.log("连接关闭");
				},
				wserror: function(){
					console.log("连接错误");
				},
				signMsgList: function(msgIds){
					// 构建批量签收对象的模型
					let dataContent = new app.dataContent(app.SIGNED,null,msgIds);
					// 发送批量签收的请求
					CHAT.chat(JSON.stringify(dataContent));
				},
				keepAlive: function(){
					// 构建心跳数据模型
					let dataContent = new app.dataContent(app.KEEPALIVE,null,null);
					// 发送心跳包
					CHAT.chat(JSON.stringify(dataContent));
					fetchUnReadMsg();
					let fetchFriendListWebview = plus.webview.getWebviewById("contact.html");
					mui.fire(fetchFriendListWebview, "refriends");
				},
				wsmessage: function(e){
					let dataContent = JSON.parse(e.data);
					let action = dataContent.action;
					if(action === app.PULL_FRIEND){
						// 重新拉取好友
						let myfaceWebview = plus.webview.getWebviewById("contact.html");
						mui.fire(myfaceWebview, "refriends");
						return false;
					}
				    let chatMsg = dataContent.chatMsg;
					let msg = chatMsg.msg;
					let friendId = chatMsg.senderId;
					let myUserId = chatMsg.receiverId;
					let chattingWebview = plus.webview.getWebviewById("chatting-" + friendId);
					let isRead = true;
					if(chattingWebview != null){
						chattingWebview.evalJS("	receiveMsg('" + msg + "')");
						chattingWebview.evalJS("	resizeScreen()");
					}else{
						playreceiveMsgRing();
						isRead = false;
					}
					// 对消息进行签收
					let dataContentSign = new app.dataContent(app.SIGNED,null,chatMsg.msgId);
					CHAT.chat(JSON.stringify(dataContentSign))
					// 保存当前消息记录
					app.saveUserChatHistory(myUserId , friendId, msg, 2);
					app.saveUserChatSnapshot(myUserId, friendId, msg, isRead)
					// 渲染快照列表
					loadingChatSnapshot();
				}
			}
			function Decrypt(word){
	            return CryptoJS.AES.decrypt(word,"crismcn").toString(CryptoJS.enc.Utf8);
	        }
			function playreceiveMsgRing(){
					p = plus.audio.createPlayer( "/mp3/msn.mp3" );
					p.play(); 
			}
			// 展示聊天快照，渲染列表
			function loadingChatSnapshot() {
				let user = app.getUserInfo();
				let chatSnapshotList = app.getUserChatSnapshot(user.userId);
				let addHtml = "";
				let ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
				let chatSnapshotLength = chatSnapshotList.length;
				if(chatSnapshotLength){
					ul_chatSnapshot.innerHTML = "";
				}
				for (let i = 0 ; i < chatSnapshotLength; i ++) {
					let chatItem = chatSnapshotList[i];
					let friendId = chatItem.friendId;
					// 根据friendId从本地联系人列表的缓存中拿到相关信息
					let friend = app.getFriendFromContactList(friendId);
					// 判断消息的已读或未读状态
					var isRead = chatItem.isRead;
					var readHtmlBefore = '';
					var readHtmlAfter = '';
					if (!isRead) {
						readHtmlBefore = '<span class="red-point">';
						readHtmlAfter = '</span>';
					}
					addHtml =  '<li friendUserId="' + friendId + '" friendNickName="' + friend.friendNickName + '" friendFaceImg="' + friend.friendFaceImg + '" class="chat-with-friend mui-table-view-cell mui-media">' +
									'<div class="mui-slider-right mui-disabled">' +
										'<a id="link_delChatRecord" friendUserId="' + friendId + '" class="mui-btn mui-btn-red">删除</a>' +
									'</div>' +
									'<div class="mui-slider-handle mui-media-body" style="overflow:initial">' +
							             	readHtmlBefore + '<img class="mui-media-object mui-pull-left" src="' + friend.friendFaceImg + '"/>' +readHtmlAfter +  friend.friendNickName + 
							            '<p class="mui-ellipsis">' + Decrypt(chatItem.msg) + '</p>' +
						            '</div>' +
							    '</li>';
					// 一条一条添加进去
					ul_chatSnapshot.insertAdjacentHTML('beforeend', addHtml);
				}
			}
			// 每次重连后获取服务器的未签收消息
			function fetchUnReadMsg() {
				var user = app.getUserInfo();
				var msgIds = ",";	// 格式：  ,1001,1002,1003,
				mui.ajax(app.serverUrl + "/msg//getUnReadMsgList?myUserId=" + user.userId,{
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(data){
						if (data.status == 200) {
							var unReadMsgList = data.data;
							// 1. 保存聊天记录到本地
							// 2. 保存聊天快照到本地
							// 3. 对这些未签收的消息，批量签收
							for (var i = 0 ; i < unReadMsgList.length ; i ++) {
								var msgObj = unReadMsgList[i];
								// 逐条存入聊天记录
								app.saveUserChatHistory(msgObj.toUserId, msgObj.fromUserId, msgObj.msg, 2);
								// 存入聊天快照
								app.saveUserChatSnapshot(msgObj.toUserId, msgObj.fromUserId, msgObj.msg, false);
								// 拼接批量接受的消息id字符串，逗号间隔
								msgIds += msgObj.chatMsgId;
								msgIds += ",";
							}
							// 因为获取了数据库记录 那就标记为已经签收。调用批量签收的方法
							if(msgIds != ","){
								CHAT.signMsgList(msgIds);
								playreceiveMsgRing();
							}
							// 刷新快照
							loadingChatSnapshot();
						}
					}
				});
			}
		</script>
	</body>

</html>